package ro.ubbcluj.cs.damate.webutils;

import org.apache.log4j.Logger;

import javax.faces.context.FacesContext;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * @author Lóránd Fazakas (lfazakas)
 *         Date: 2011.10.10.
 *         Time: 14:59
 */
public class MessageProvider {

    private static Logger log = Logger.getLogger(MessageProvider.class);

	public static ResourceBundle getBundle() {
        FacesContext context = JSFUtil.facesContext();
        if (context != null) {
            return context.getApplication().getResourceBundle(context, "msg");
        } else {
            return null;
        }
	}

	public static String getValue(String key) {
        ResourceBundle bundle = getBundle();

		try {
            if (bundle != null) {
                return bundle.getString(key);
            } else {
                return key;
            }
		} catch (MissingResourceException e) {
			return "???" + key + "??? not found";
		}
	}

    public static String getValue(String key, String... params) {
		String message = null;
		try {
			message = getBundle().getString(key);
            if (params != null && params.length > 0) {
                return MessageFormat.format(message, params);
            }
		} catch (MissingResourceException e) {
			message = "???" + key + "??? not found";
		} catch (Exception e) {
            message = "???" + key + "??? could not be read.";
            log.warn("error reading message bundle key: " + key, e);
        }
		return message;
	}
}
